*************************************************************************************************************************************;
*This do file estimates the measurement model in Appendix Equation B-1 and generates Table B-1: Estimates for the Measurement Model;
*************************************************************************************************************************************;

use $scratch/final_skills_peers.dta, clear

egen idgrade = group(idschool class)

egen school_size = count(idschool) , by(idschool)
egen grade_size = count(idgrade), by(idgrade)


keep if class >=9 & class<=12

********************************************************************************;
*Estimate Measurement System for Skills;
*Factor model (Appendix Equation B-1):
* M = mu + lambda log(theta) + e ;
*(where theta represents the unobserved skills, while M represent the measured skills);
********************************************************************************;

*Location;
forvalues i = 1 (1) 5 {
sum cogn`i' if class==9
gen mu_cogn`i' = r(mean)
}


*Factor Loading;
forvalues i = 1 (1) 5 {
local ind = 1
forvalues j = 1 (1) 5 {
forvalues k = 1 (1) 5 {

if (`i' != `j') & ( `j' != `k') & ( `i' != `k' ) {

qui corr cogn`i' cogn`j' if class==9 , covariance 
local cov1 = r(cov_12)

qui corr cogn`i' cogn`k' if class==9, covariance 
local cov2 = r(cov_12)

qui corr cogn`k' cogn`j' if class==9, covariance 
local cov3 = r(cov_12)

gen lambda_cogn`i'_`ind' = sqrt( `cov1'*`cov2'/`cov3' )

local ind = `ind' + 1
}
}
}

order lambda_cogn`i'_1 - lambda_cogn`i'_12 

egen lambda_cogn`i' = rowmean(lambda_cogn`i'_1 lambda_cogn`i'_2 lambda_cogn`i'_3 ///
							  lambda_cogn`i'_4 lambda_cogn`i'_5 lambda_cogn`i'_6 ///
							  lambda_cogn`i'_7 lambda_cogn`i'_8 lambda_cogn`i'_9 ///
							  lambda_cogn`i'_10 lambda_cogn`i'_11 lambda_cogn`i'_12)

drop lambda_cogn`i'_*							  
							  
*Age/grade-invariance assumption;
gen cogn`i'_tilde = (cogn`i' - mu_cogn`i')/lambda_cogn`i'			  


							  
}

***************************************************;
*Table B-1: Estimates for the Measurement Model;
***************************************************;
sum mu* lambda*

save $scratch\final_data_for_model.dta, replace
